import io from "socket.io-client"
import store from "../store";
import { Notification , MessageBox} from "element-ui";
//模块作用，收发消息
//创建连接
const socket = io()

//进行连接的监听
socket.on('connect',()=>{
    console.log("和服务器已经建立连接");
})

//监听room_info收消息
socket.on('room_info',({nicknames,holder,lines})=>{
    // console.log(nicknames,holder,lines);
    store.commit('updateNicknames', nicknames);
    store.commit('updateHolder', holder);
    store.commit('updateLines', lines);

})
//监听user_enter,通知：有人进房间了
socket.on('user_enter',nickname=>{
    store.commit('addToNicknames', nickname);
    
})

//监听soket连接，控制按钮
socket.on('connect',()=>{
    store.commit('updateConnected',true)
})
//监听断开
socket.on('disconnect',()=>{
    store.commit('updateConnected',false)
})
  //处理游戏成功开始
    socket.on('game_started',holder=>{
        store.commit('updateHolder',holder)
        Notification.success(`${holder}作为主持人已经成功开始游戏`)
    })
  //开始但是不能重复开始
    socket.on('already_started',holder=>{
        store.commit('updateHolder',holder)
        Notification.alert(`当前游戏已经开始主持人是：${holder}`)
    })
//监听游戏的终止，重置信息
socket.on('game_stoped',()=>{
    //清除相关数据
    store.commit('updateHolder','')
    store.commit('updateLines',[])

    //弹出提示消息
    Notification.warning('主持人终止了当前游戏')
})

//监听线的绘制
socket.on('starting_line',line=>{
    store.commit('drawNewLine',line)
})
socket.on('updating_line',line=>{
    store.commit('updateNewLine',line)

})


//猜答案结果

socket.on('game_answered',({ alreadyDone, success, nickname, answer })=>{
    if(alreadyDone){
        MessageBox.alert('当前答案已经被猜中了')
        return
    }
    if (!success) {
        Notification.error(`玩家${nickname},猜的答案不对 ${answer}`)
        return
    }
    // if()
    //只剩下答对了的
    MessageBox.alert(`玩家 ${nickname} 猜中了正确答案`)
})

//广播退出
socket.on('user_leave',nickname=>{
    store.commit('delFromNicknames',nickname)
    
    if(nickname == store.state.holder){
        store.commit('updateHolder','')
        store.commit('updateLines',[])
        Notification.error('主持人离开了游戏')
    }
})

//导出
export default socket